<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<div th:replace="common/common::html"></div>
<head>
    <meta charset="UTF-8">
    <link th:href="@{/assets/css/page.css}" rel="stylesheet"/>
    <title th:text="#{file.manager.title}">Title</title>
    <script th:inline="javascript">
        const FILE_TYPE_FILE = 0
        const FILE_TYPE_FOLDER = 1
        var _gridWidth;
        var _gridHeight;

        //页面自适应
        function resizePageSize(){
            _gridWidth = $(document).width()-12;/*  -189 是去掉左侧 菜单的宽度，   -12 是防止浏览器缩小页面 出现滚动条 恢复页面时  折行的问题 */
            _gridHeight = $(document).height()-65 -40; /* -32 顶部主菜单高度，   -90 查询条件高度*/
        }

        // 调整预览框大小的函数
        function adjustPreviewSize() {
            var dialog = $("#pre-file-dialog-id");
            var windowWidth = $(window).width();
            var windowHeight = $(window).height();

            // 设置对话框最大尺寸为窗口的90%
            var maxWidth = windowWidth * 0.9;
            var maxHeight = windowHeight * 0.9;

            // 计算合适的对话框尺寸
            var dialogWidth = Math.min(maxWidth, windowWidth > 1200 ? 1200 : windowWidth * 0.9);
            var dialogHeight = Math.min(maxHeight, windowHeight * 0.85);

            dialog.dialog("option", "width", dialogWidth);
            dialog.dialog("option", "maxHeight", maxHeight);

            // 调整内容区域高度
            if (dialog.is(":visible")) {
                var headerHeight = dialog.find(".ui-dialog-titlebar").outerHeight() || 50;
                var buttonHeight = dialog.find(".ui-dialog-buttonpane").outerHeight() || 50;
                var contentHeight = dialogHeight - headerHeight - buttonHeight - 20; // 减去内边距
                $("#pre-file-content").css("height", contentHeight + "px");

                // 调整媒体元素大小
                adjustMediaElements();
            }
        }

        // 调整媒体元素大小以适应容器
        function adjustMediaElements() {
            var content = $("#pre-file-content");
            var contentWidth = content.width();
            var contentHeight = content.height();

            // 调整视频元素
            content.find("video").each(function() {
                $(this).css({
                    "max-width": "100%",
                    "max-height": (contentHeight - 80) + "px" // 减去元数据区域高度
                });
            });

            // 调整图片元素
            content.find("img").each(function() {
                $(this).css({
                    "max-width": "100%",
                    "max-height": (contentHeight - 80) + "px" // 减去元数据区域高度
                });
            });

            // 调整iframe（文档预览）
            content.find("iframe").each(function() {
                $(this).css({
                    "width": "100%",
                    "height": contentHeight + "px"
                });
            });
        }

        $(function () {
            resizePageSize();
            var _columnWidth = (_gridWidth-150)/5;
            $("#flexigrid-id").flexigrid({
                width : _gridWidth,
                height : _gridHeight,
                url : /*[[@{/file/queryFileInfoListByPage}]]*/"",
                dataType : 'json',
                colModel : [
                    {display : 'fileUuid',name : 'fileUuid',width : 150,sortable : false,align : 'center',hide : 'true'},
                    {display : /*[[#{file.name}]]*/"",name : 'fileName',width : _columnWidth, sortable : true,align : 'center',
                        process: function(v,_trid,_row) {
                            var html = `<div style="display: flex; width: 100px; ">`
                            if(_row.fileType === FILE_TYPE_FOLDER){
                                html += `<a href="#" style="color: #00b1ef" class="btn" onclick="enterDir('${_row.fileUuid}','${_row.filePath}')"><i class="glyphicon glyphicon-folder-close" style="margin-right: 5px"></i>
                                        <span>${v}</span>
                                   </a>`
                            }else{
                                html += `<a href="#" style="color: #f7ba2a" class="btn" onclick="preFile('${_row.fileUuid}','${v}', '${_row.fileCapacity}', '${_row.modtime}')"><i class="glyphicon glyphicon-file" style="margin-right: 5px"></i>
                                        <span>${v}</span>
                                   </a>`
                            }
                            html += `</div>`
                            return html;
                        }},
                    {display : /*[[#{file.size}]]*/"",name : 'fileCapacity',width : _columnWidth, sortable : true,align : 'center',
                        process: function(v) {
                            return formatFileSize(v);
                        }},
                    {display : /*[[#{file.last.time}]]*/"",name : 'modtime',width : _columnWidth, sortable : true,align : 'center'},
                    {display : /*[[#{common.operation}]]*/"",name : 'fileUuid',width : _columnWidth, sortable : true,align : 'center',process: function(v,_trid,_row) {
                            var html = `<div>`
                            if (_row.fileType === FILE_TYPE_FILE) {
                                if ([[${#authorization.expression("hasRole('ROLE_cldk_data_user_mod')")}]]) {
                                    html += `<a href="#" class="btn" onclick="modifyFileInfo('${v}')" title=[[#{common.modify}]]><i class="glyphicon glyphicon-pencil"></i></a>`
                                }
                                if ([[${#authorization.expression("hasRole('ROLE_cldk_data_user_del')")}]]) {
                                    html += `<a href="#" class="btn" onclick="deleteFileInfo('${v}','${_row.fileName}')" title=[[#{common.delete}]]><i class="glyphicon glyphicon-trash"></i></a>`
                                }
                                html += `<a href="#" class="btn" onclick="shareFileInfo('${v}','${_row.fileName}')" title=[[#{file.share.btn}]]><i class="glyphicon glyphicon-share"></i></a>`

                                var url =/*[[@{/file/downFile}]]*/'';
                                url += "/" + v;
                                html += `<a href=${url} class="btn"  title=[[#{file.download.btn}]] target="_blank"><i class="glyphicon glyphicon-download"></i></a>`;

                            }else {
                                html += `--`
                            }
                            html += `<div>`
                            return html;
                        }},
                ],
                resizable : false, //resizable table是否可伸缩
                useRp : true,
                usepager : true, //是否分页
                autoload : false, //自动加载，即第一次发起ajax请求
                hideOnSubmit : true, //是否在回调时显示遮盖
                showcheckbox : true, //是否显示多选框
                // rowhandler : rowDbclick, //是否启用行的扩展事情功能,在生成行时绑定事件，如双击，右键等
                rowbinddata : true
            });
            query();


            /**
             * 修改文件对话框
             */
            $("#modify-file-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{file.modify.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("form#modify-file-form-id input.form-control").checkDom()
                            if(!flag){
                                return
                            }
                            $("#modify-file-form-id").submit()
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })//end dialog
            /**
             * 修改文件异步表单
             */
            $("#modify-file-form-id").ajaxForm({
                dataType: "json",
                success : function(data) {
                    message(data.msg);
                    query();
                    if(data.success){
                        $("#modify-file-dialog-id").dialog('close')
                    }
                },
                error : function() {
                    message(/*[[#{common.error}]]*/'');
                },

            })//end ajaxForm



            $("#flexigrid-id").flexReload();

            //    创建文件夹对话框
            $("#mkdir-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{file.mkdir.dialog.tip}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var parentId = $("#file-folder-id").attr("parent-id");
                            var flag = $("#file-folder-name-id").checkDom();
                            if(!flag) {
                                return
                            }

                            var folderName = $("#file-folder-name-id").val();

                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType: 'json',
                                url: /*[[@{/file/mkdirFileInfo}]]*/'',
                                data: [
                                    {name:"parentId",value:parentId},
                                    {name:"folderName",value:folderName}
                                ],
                                success: function (data) {
                                    message(data.msg)
                                    query();
                                    $("#file-folder-name-id").val(''); // 清空输入框
                                    $("#mkdir-dialog-id").dialog('close')
                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    },
                ]
            })

            //删除文件对话框
            $("#delete-file-dialog-id").dialog({
                autoOpen : false,
                width : 400,
                modal : true,
                resizable : false,
                title: /*[[#{file.delete.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var ids =  $("#delete-file-dialog-id").attr("ids")

                            $.ajax({
                                type: 'post',
                                async: false,
                                dataType : 'json',
                                url: /*[[@{/file/deleteFileByIds}]]*/'',
                                data: [{name:"ids",value:ids}],
                                success: function (data) {
                                    // console.info('deleteFileByIds:' +JSON.stringify(data))
                                    message(data.msg)
                                    if(data.success){
                                        $("#delete-file-dialog-id").dialog('close')
                                        query()
                                    }

                                },
                                error: function(msg){
                                    message(/*[[#{common.error}]]*/'');
                                }
                            });
                        }
                    },//end button
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }//end buttons
                ]
            })

            //文件上传对话框
            $("#upload-file-dialog-id").dialog({
                autoOpen: false,
                width: 400,
                modal: true,
                resizable: false,
                title: /*[[#{file.upload.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            var flag = $("#upload-file-name-id").checkDom();
                            if (!flag) {
                                return;
                            }
                            $("#upload-file-form-id").submit();
                        }
                    },
                    {
                        text: /*[[#{common.cancel}]]*/'',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            })
            $("#upload-file-form-id").ajaxForm({
                dataType: "json",
                success: function(data) {
                    query();
                    $("#upload-file-dialog-id").dialog('close');
                },
                error: function() {
                    message(/*[[#{common.error}]]*/'');
                }
            })

            $("#share-file-dialog-id").dialog({
                autoOpen: false,
                width: 800,
                modal: true,
                resizable: false,
                title: /*[[#{file.share.dialog.tip}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function () {
                            $(this).dialog("close");

                        }
                    }]
            })

            // 在线文件预览
            $("#pre-document-dialog-id").dialog({
                autoOpen: false,
                width: 800,
                modal: true,
                resizable: false,
                // title: /*[[#{file.upload.dialog.title}]]*/'',
                buttons: [
                    {
                        text: /*[[#{common.confirm}]]*/'',
                        click: function() {
                            $( this ).dialog("close")
                        }
                    }
                ]
            })

            // <!-- 在线音视频预览 -->
            $("#pre-file-dialog-id").dialog({
                autoOpen: false,
                width: "auto",  // 自适应宽度
                height: "auto",  // 自适应高度
                modal: true,
                resizable: true,
                open: function() {
                    // 确保对话框正确显示
                    $(this).css("display", "block");
                    // 调整预览大小
                    adjustPreviewSize();
                },
                buttons: [
                    {
                        text: /*[[#{common.close}]]*/'',
                        click: function() {
                            $(this).dialog("close");
                        }
                    }
                ]
            })

            // 监听窗口大小变化，调整预览框
            $(window).on('resize', function() {
                adjustPreviewSize();
                resizePageSize();
            });

        });//end ready function

        /**
         * 文件同步
         */
        function  syncFileData() {
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/syncFileData}]]*/'',
                data: [],
                success: function (data) {
                    message(data.msg)


                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });

        }

        /**
         * 表格查询
         */
        function query() {

            var parentId = $("#file-folder-id").attr("parent-id");
            var fileName= $("#file-name-id").val().trim();



            $("#flexigrid-id").flexOptions({
                extParam:[
                    {name:"parentId",value:parentId},
                    {name:"fileName",value:fileName}
                ],

            }).flexReload()
        }
        //文件名修改q
        //双击事件
        function rowDbclick(r){
            $(r).dblclick(
                function() {
                    var columnsArray = $(r).attr('ch').split("_FG$SP_");
                    // console.info(columnsArray);

                    var fileUuid = columnsArray[0]

                    modifyFileInfo(fileUuid);



                });
        }

        /**
         * 修改文件信息q
         * @param fileUuid
         */
        function modifyFileInfo(fileUuid) {
            $.ajax({
                    type: 'post',
                    async: false,
                    dataType : 'json',
                    url: /*[[@{/file/queryFileInfoById}]]*/'',
                    data: [{name:"fileUuid",value:fileUuid}],
                    success: function (data) {
                        var list = $("form#modify-file-form-id input.form-control");
                        list.each(function (index,item) {
                            var name = $(item).attr("name")
                            $(this).val(data[name])
                        })

                        $("form#modify-file-form-id input.form-control").checkDom()
                        $("#modify-file-dialog-id").dialog('open')

                    },
                    error: function(msg){
                        message(/*[[#{common.error}]]*/'');
                    }
                }
            );
        }



        /**
         * 进入文件夹
         */
        function enterDir(fileUuid,filePath) {
            $("#file-folder-id").attr("parent-id",fileUuid)
            if(fileUuid === -1) {
                $("#file-folder-id").val("/")
            }
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/queryFileInfoById}]]*/'',
                data: [
                    {name:"fileUuid",value:fileUuid}
                ],
                success: function (data) {
                    if (data){
                        $("#file-folder-id").val(data['filePath'])

                    }else {
                        $("#file-folder-id").val("/")
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });

            $("#file-folder-id").val(filePath)

            query()
        }

        /**
         * 进入上级文件夹
         */
        function upDir() {
            var fileUuid = $("#file-folder-id").attr("parent-id");
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/queryFileInfoById}]]*/'',
                data: [
                    {name:"fileUuid",value:fileUuid}
                ],
                success: function (data) {
                    if (data){
                        enterDir(data['parentUuid'])

                    }else {
                        $("#file-folder-id").val("/")
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

        /**
         * 创建文件夹
         */
        function mkdirFun() {
            $("#mkdir-dialog-id").dialog('open')

        }

        //删除文件
        function bathDeleteFile() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            $("#delete-file-dialog-id").attr('ids',ids)

            // console.info("bathDeleteFile idx:" + JSON.stringify(ids))
            var niceNameArray = $("#flexigrid-id").getFlexigridiAttrByIndex(4)
            $("#delete-file-list-id").text(niceNameArray.join(","))
            $("#delete-file-dialog-id").dialog('open')

        }

        // 单独删除文件
        function deleteFileInfo(fileUuid,fileName) {
            $("#delete-file-dialog-id").attr('ids',fileUuid)
            $("#delete-file-list-id").text(fileName)
            $("#delete-file-dialog-id").dialog('open')
        }

        /**
         * 文件复制
         */
        function copyFile() {
            var ids = $("#flexigrid-id").getFlexigridiAttrByIndex(0)
            if(ids.length === 0){
                message(/*[[#{common.empty}]]*/'');
                return;
            }
            $("#file-copy-btn-id").attr('ids',ids)
            var parentId = $("#file-folder-id").attr("parent-id");
            $("#file-copy-btn-id").attr('src-uuid',parentId)
            $("#file-past-btn-id").removeClass('hidden')
            $("#file-past-num-id").text(ids.length+"")
        }
        /**
         * 文件粘贴
         */
        function pasteFile() {
            // $("#file-copy-btn-id").attr('ids',ids)
            var parentId = $("#file-folder-id").attr("parent-id");
            var srcUuid = $("#file-copy-btn-id").attr("src-uuid");
            if (parentId === srcUuid){
                message(/*[[#{file.paste.fail.same.folder}]]*/"")
                return
            }
            var ids = $("#file-copy-btn-id").attr('ids');
            $.ajax({
                type: 'post',
                async: false,
                dataType : 'json',
                url: /*[[@{/file/copyFile}]]*/'',
                data: [
                    {name:"srcUuidList",value:ids},
                    {name:"parentId",value:parentId},
                ],
                success: function (data) {
                    message(data.msg)
                    if(data.success){
                        $("#file-past-btn-id").addClass("hidden");
                    }
                },
                error: function(msg){
                    message(/*[[#{common.error}]]*/'');
                }
            });

        }

        /**
         * 格式化文件大小显示
         * @param {Number} bytes - 文件大小（字节）
         * @returns {String} 格式化后的的大小字符串（B/KB/MB/GB）
         */
        function formatFileSize(bytes) {
            // 处理无效值
            if (bytes === null || bytes === undefined || isNaN(bytes)) {
                return '未知大小';
            }

            // 定义单位和转换比例
            const units = ['B', 'KB', 'MB', 'GB'];
            let size = parseFloat(bytes);
            let unitIndex = 0;

            // 转换单位直到合适的规模
            while (size >= 1024 && unitIndex < units.length - 1) {
                size /= 1024;
                unitIndex++;
            }

            // 保留两位小数并拼接单位
            return `${size.toFixed(2)} ${units[unitIndex]}`;
        }

        /**
         * 视频在线预览模块
         */
        function videoPreview(fileUuid, fileName, fileSize, fileModified) {
            // 先显示对话框
            $("#pre-file-dialog-id").dialog('open');

            // 设置标题
            $("#pre-file-dialog-id").dialog('option', 'title', fileName);

            // 显示加载状态
            $("#pre-file-content").html(`
        <div class="loading-state" style="text-align: center; padding: 60px 0;">
            <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 10px;"></i>
            <div>正在加载视频...</div>
        </div>
    `);

            // 获取视频分享链接
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: /*[[@{/file/getShareUrl}]]*/'',
                data: [{name: "fileUuid", value: fileUuid}],
                success: function (data) {
                    console.info("videoPreview:" + JSON.stringify(data));

                    if (data && data.success && data.code) {
                        var url = data.code;
                        var fileExt = fileName.split('.').pop().toLowerCase();

                        // 确定视频MIME类型
                        var mimeType = 'video/mp4';
                        if (fileExt === 'avi') mimeType = 'video/x-msvideo';
                        if (fileExt === 'mov') mimeType = 'video/quicktime';
                        if (fileExt === 'mkv') mimeType = 'video/x-matroska';
                        if (fileExt === 'flv') mimeType = 'video/x-flv';
                        if (fileExt === 'wmv') mimeType = 'video/x-ms-wmv';

                        // 显示视频播放器
                        $("#pre-file-content").html(`
                    <div style="padding: 10px; height: 100%; box-sizing: border-box;">
                        <div class="file-meta" style="margin-bottom: 10px; color: #666; font-size: 0.9rem;">
                            <span>大小: ${formatFileSize(fileSize)}</span>
                            <span style="margin: 0 10px;">|</span>
                            <span>修改时间: ${fileModified}</span>
                        </div>
                        <video controls style="width: 100%; background-color: #000; border-radius: 4px; max-height: calc(100% - 80px);">
                            <source src="${url}" type="${mimeType}">
                            您的浏览器不支持HTML5视频播放，请下载文件查看。
                        </video>
                    </div>
                `);

                        // 调整视频大小
                        adjustMediaElements();
                    } else {
                        $("#pre-file-content").html(`
                    <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                        无法获取视频预览链接: ${data ? data.msg : '未知错误'}
                    </div>
                `);
                    }
                },
                error: function (xhr, status, error) {
                    console.error("视频预览请求错误:", status, error);
                    $("#pre-file-content").html(`
                <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                    视频预览失败: ${error || /*[[#{common.error}]]*/''}
                </div>
            `);
                }
            });
        }

        /**
         * 音频在线预览模块
         */
        function audioPreview(fileUuid, fileName, fileSize, fileModified) {
            // 显示对话框（先于加载数据显示，确保用户知道操作已响应）
            $("#pre-file-dialog-id").dialog('open');

            // 设置对话框标题
            $("#pre-file-dialog-id").dialog('option', 'title', fileName);

            // 清空预览容器并显示加载状态
            $("#pre-file-content").html(`
        <div class="loading-state" style="text-align: center; padding: 60px 0;">
            <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 10px;"></i>
            <div>正在加载音频...</div>
        </div>
    `);

            // 获取音频分享链接
            $.ajax({
                type: 'post',
                async: true,  // 改为异步加载，避免阻塞UI
                dataType: 'json',
                url: /*[[@{/file/getShareUrl}]]*/'',
                data: [{name: "fileUuid", value: fileUuid}],
                success: function (data) {
                    console.info("audioPreview:" + JSON.stringify(data));

                    // 检查返回数据是否有效
                    if (data && data.success && data.code) {
                        var url = data.code;
                        var fileExt = fileName.split('.').pop().toLowerCase();

                        // 确定音频MIME类型
                        var mimeType = 'audio/mpeg';
                        if (fileExt === 'wav') mimeType = 'audio/wav';
                        if (fileExt === 'ogg') mimeType = 'audio/ogg';
                        if (fileExt === 'flac') mimeType = 'audio/flac';
                        if (fileExt === 'aac') mimeType = 'audio/aac';

                        // 显示音频播放器
                        $("#pre-file-content").html(`
                    <div style="padding: 20px; background-color: #f8f9fa; border-radius: 4px; height: 100%; box-sizing: border-box;">
                        <div class="file-meta" style="margin-bottom: 15px; color: #666; font-size: 0.9rem;">
                            <span>大小: ${formatFileSize(fileSize)}</span>
                            <span style="margin: 0 10px;">|</span>
                            <span>修改时间: ${fileModified}</span>
                        </div>
                        <audio controls style="width: 100%; margin-bottom: 15px;">
                            <source src="${url}" type="${mimeType}">
                            您的浏览器不支持HTML5音频播放，请下载文件查看。
                        </audio>
                    </div>
                `);
                    } else {
                        // 处理无效响应
                        $("#pre-file-content").html(`
                    <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                        无法获取音频预览链接: ${data ? data.msg : '未知错误'}
                    </div>
                `);
                    }
                },
                error: function (xhr, status, error) {
                    // 详细错误信息
                    console.error("音频预览请求错误:", status, error);
                    $("#pre-file-content").html(`
                <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                    音频预览失败: ${error || /*[[#{common.error}]]*/''}
                </div>
            `);
                }
            });
        }

        /**
         * 图片在线预览模块
         */
        function imagePreview(fileUuid, fileName, fileSize, fileModified) {
            // 显示对话框
            $("#pre-file-dialog-id").dialog('open');

            // 设置标题
            $("#pre-file-dialog-id").dialog('option', 'title', fileName);

            // 显示加载状态
            $("#pre-file-content").html(`
        <div class="loading-state" style="text-align: center; padding: 60px 0;">
            <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 10px;"></i>
            <div>正在加载图片...</div>
        </div>
    `);

            // 获取图片分享链接
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: /*[[@{/file/getShareUrl}]]*/'',
                data: [{name: "fileUuid", value: fileUuid}],
                success: function (data) {
                    console.info("imagePreview:" + JSON.stringify(data));

                    if (data && data.success && data.code) {
                        var url = data.code;
                        var fileExt = fileName.split('.').pop().toLowerCase();

                        // 确定图片MIME类型
                        var mimeType = 'image/jpeg';
                        if (fileExt === 'png') mimeType = 'image/png';
                        if (fileExt === 'gif') mimeType = 'image/gif';
                        if (fileExt === 'bmp') mimeType = 'image/bmp';
                        if (fileExt === 'webp') mimeType = 'image/webp';

                        // 显示图片预览
                        $("#pre-file-content").html(`
                    <div style="padding: 10px; height: 100%; box-sizing: border-box; text-align: center;">
                        <div class="file-meta" style="margin-bottom: 10px; color: #666; font-size: 0.9rem;">
                            <span>大小: ${formatFileSize(fileSize)}</span>
                            <span style="margin: 0 10px;">|</span>
                            <span>修改时间: ${fileModified}</span>
                        </div>
                        <img src="${url}"
                             alt="${fileName}"
                             style="max-width: 100%; max-height: calc(100% - 80px); border-radius: 4px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);"
                             type="${mimeType}">
                    </div>
                `);

                        // 调整图片大小
                        adjustMediaElements();
                    } else {
                        $("#pre-file-content").html(`
                    <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                        无法获取图片预览链接: ${data ? data.msg : '未知错误'}
                    </div>
                `);
                    }
                },
                error: function (xhr, status, error) {
                    console.error("图片预览请求错误:", status, error);
                    $("#pre-file-content").html(`
                <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                    图片预览失败: ${error || /*[[#{common.error}]]*/''}
                </div>
            `);
                }
            });
        }

        /**
         * 文件预览分发器 - 根据文件类型调用相应的预览模块
         */
        function preFile(fileUuid, fileName, fileSize, fileModified) {
            // 清空预览容器
            $("#pre-file-content").html('');

            // 获取文件扩展名并转为小写
            var fileExt = fileName.split('.').pop().toLowerCase();

            // 文档类型 (docx)
            var regDoc = new RegExp("^docx$");
            if (regDoc.test(fileExt)) {
                // 设置对话框标题
                $("#pre-file-dialog-id").dialog('option', 'title', fileName);

                // 显示加载状态
                $("#pre-file-content").html(`
            <div class="loading-state" style="text-align: center; padding: 60px 0;">
                <i class="fas fa-spinner fa-spin" style="font-size: 2rem; margin-bottom: 10px;"></i>
                <div>正在加载文档...</div>
            </div>
        `);

                // 显示对话框
                $("#pre-file-dialog-id").dialog('open');

                // 获取文档分享链接
                $.ajax({
                    type: 'post',
                    async: true,
                    dataType: 'json',
                    url: /*[[@{/file/getShareUrl}]]*/'',
                    data: [{name: "fileUuid", value: fileUuid}],
                    success: function (data) {
                        console.info("docx预览响应:", JSON.stringify(data))
                        var url = data['code'];
                        if (url) {
                            // 处理URL特殊字符
                            url = url.replaceAll("&", "%26")
                            url = url.replaceAll("?", "%3F")
                            $("#pre-file-content").html(`
                        <iframe src="https://view.xdocin.com/xdoc?_xdoc=${url}"
                                style="width: 100%; height: 100%; border: none;"></iframe>
                    `);

                            // 调整iframe大小
                            adjustMediaElements();
                        } else {
                            $("#pre-file-content").html(`
                        <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                            无法获取文档预览链接
                        </div>
                    `);
                        }
                    },
                    error: function (msg) {
                        $("#pre-file-content").html(`
                    <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                        文档预览失败: ${/*[[#{common.error}]]*/''}
                    </div>
                `);
                    }
                });
            }
            // 图片类型
            else if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileExt)) {
                imagePreview(fileUuid, fileName, fileSize, fileModified);
            }
            // 视频类型
            else if (['mp4', 'avi', 'mov', 'mkv', 'flv', 'wmv', 'webm', 'mpeg', 'mpg'].includes(fileExt)) {
                videoPreview(fileUuid, fileName, fileSize, fileModified);
            }
            // 音频类型
            else if (['mp3', 'wav', 'ogg', 'flac', 'aac'].includes(fileExt)) {
                audioPreview(fileUuid, fileName, fileSize, fileModified);
            }
            // 不支持的文件类型
            else {
                // 设置对话框标题
                $("#pre-file-dialog-id").dialog('option', 'title', fileName);

                // 显示不支持信息
                $("#pre-file-content").html(`
            <div class="error-message" style="color: #dc3545; text-align: center; padding: 20px;">
                <i class="fas fa-exclamation-triangle" style="font-size: 2rem; margin-bottom: 15px;"></i>
                <div>不支持的文件类型</div>
                <div style="margin-top: 10px; font-size: 0.9rem; color: #666;">
                    文件格式: .${fileExt}
                </div>
            </div>
        `);

                // 显示对话框
                $("#pre-file-dialog-id").dialog('open');
            }
        }

        /**
         * 文件分享
         * @param fileuuid
         * @param fileName
         */
        function shareFileInfo(fileUuid, fileName) {
            $("#share-file-name").attr("fileUuid", fileUuid);
            $("#share-file-name").text(fileName);
            $("#share-file-dialog-id").dialog('open')
        }

        /**
         * 查询分享地址
         */
        function queryShareUrl() {
            var fileUuid = $("#share-file-name").attr("fileUuid")
            var fileValidity = $("#share-file-validity").val()
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: /*[[@{/file/queryShareUrl}]]*/'',
                data: [
                    {name: "fileUuid", value: fileUuid},
                    {name: "fileValidity", value: fileValidity},
                ],
                success: function (data) {
                    console.info(`queryShareUrl:${JSON.stringify(data)}`)
                    $("#share-file-url-id").val(data['code']);
                },
                error: function (msg) {
                    message(/*[[#{common.error}]]*/'');
                }
            });
        }

    </script>
    <style>
        a.hidden{
            display: none;

        }
        #file-past-num-id{
            color:#ff0000 ;
        }

        /* 预览框样式优化 */
        .preview-container {
            overflow: auto;
            box-sizing: border-box;
        }

        /* 确保视频和图片在容器中居中显示 */
        .preview-container video,
        .preview-container img {
            display: block;
            margin: 0 auto;
        }
    </style>
</head>
<body>

<header>
    <a href="#" class="btn-info btn" onclick="upDir()" th:title="#{file.up.folder}">
        <i class="glyphicon glyphicon-open"></i>
    </a>
    <input id="file-folder-id" value="/" parent-id="-1">
    <input id="file-name-id" th:placeholder="#{file.name.plc}">
    <a href="#" class="btn-info btn" onclick="query()">
        <i class="glyphicon glyphicon-search"></i>
        <span th:text="#{common.query}"></span>
    </a>

    <a href="#" class="btn-info btn" onclick="syncFileData()">
        <i class="glyphicon glyphicon-refresh"></i>
        <span th:text="#{file.sync.data}"></span>
    </a>



    <!--        文件上传-->
    <a href="#" class="btn-info btn" onclick="uploadFile()">
        <i class="glyphicon glyphicon-upload"></i>
        <span th:text="#{file.upload.btn}"></span>
    </a>

    <a href="#" class="btn-info btn">
        <i class="glyphicon  glyphicon-arrow-down"></i>
        <span th:text="#{file.download}"></span>
    </a>

    <a href="#" class="btn-info btn"  onclick="bathDeleteFile()">
        <i class="glyphicon  glyphicon-trash"></i>
        <span th:text="#{file.delete}"></span>
    </a>
    <a href="#" class="btn-info btn" onclick="shareFile()">
        <i class="glyphicon glyphicon-share"></i>
        <span th:text="#{user.share}"></span>
    </a>

    <a id="file-copy-btn-id" href="#" class="btn-info btn" onclick="copyFile()">
        <i class="glyphicon glyphicon-copy"></i>
        <span th:text="#{file.copy.btn}"></span>
    </a>

    <a id="file-past-btn-id" href="#" class="btn-info btn hidden" onclick="pasteFile()">
        <i class="glyphicon glyphicon-paste"></i>
        <span th:text="#{file.paste.btn}"></span>

        (
        <span id="file-past-num-id"></span>
        )
    </a>

    <!--        创建文件夹-->
    <a href="#" class="btn-info btn" onclick="mkdirFun()">
        <i class="glyphicon glyphicon-book"></i>
        <span th:text="#{file.mkdir}"></span>
    </a>
</header>

<table id="flexigrid-id"></table>

<!--    创建文件对话框-->
<div id="mkdir-dialog-id" style="display: none">
    <div class="form-group">
        <span th:text="#{file.folder.name}"></span>
        <input id="file-folder-name-id" class="form-control" pattern="^.+$">
    </div>
</div>

<div id="delete-file-dialog-id" style="display: none">
    <span id="delete-file-list-id"></span>
</div>

<div id="share-file-dialog-id" style="display: none">
    <div class="form-group">
        <span th:text="#{file.name}"></span>
        <span class="form-control" id="share-file-name"></span>
    </div>

    <div class="form-group">
        <span th:text="#{file.share.validity}"></span>
        <input class="form-control" id="share-file-validity" type="number" value="1" onchange="queryShareUrl()">
    </div>

    <div class="form-group">
        <span th:text="#{file.share.url}"></span>
        <textarea class="form-control" id="share-file-url-id" style="height: 60px"></textarea>
    </div>
</div>
<!--文件上传-->
<!-- 添加文件上传的隐藏表单/输入框 -->
<div id="upload-file-dialog-id" style="display: none;">
    <form id="upload-file-form-id" enctype="multipart/form-data" method="post" th:action="@{/file/uploadFile}">
        <input name="parentId" id="upload-file-parent-id" type="hidden">
        <div class="form-group">
            <span th:text="#{file.name}"></span>
            <input name="fileName" id="upload-file-name-id" pattern="^.+$" type="file">
        </div>
    </form>
</div>
<!-- 文件名修改q-->
<div id="modify-file-dialog-id" style="display: none">

    <form id="modify-file-form-id" method="post" th:action="@{/file/modifyFileInfoById}">
        <div class="form-group">
            <span  th:text="#{file.uuid}"></span>
            <input class="form-control" name="fileUuid" readonly>
        </div>

        <div class="form-group">
            <span  th:text="#{file.name}"></span>
            <input class="form-control" name="fileName" pattern="^.{4,}$">
        </div>

    </form>
</div>

<!--    // 在线预览文件-->
<div id="pre-document-dialog-id" style="display: none">
    <iframe id="pro-document-iframe-id" style="width: 100%;height: 400px">

    </iframe>

</div>

<div id="pre-file-dialog-id" style="display: none;">
    <div id="pre-file-content" class="preview-container">
        <!-- 预览内容将通过JavaScript动态加载 -->
    </div>
</div>


<script>
    // 删除文件信息函数 - 与批量删除保持一致
    function deleteFileInfo(fileId, fileName) {
        // 设置文件ID并打开删除对话框
        $("#delete-file-dialog-id").attr('ids', fileId);
        $("#delete-file-list-id").text(fileName);
        $("#delete-file-dialog-id").dialog('open');
    }



    // 分享函数已删除，保留按钮
    function shareFileSingle(fileUuid) {
        alert('分享功能已移除');
    }

    function shareFile() {
        alert('分享功能已移除');
    }

    // 显示文件选择框
    function showUploadDialog() {
        document.getElementById("uploadDialog").style.display = "block";
    }



    // 执行文件上传
    function uploadFile() {
        $("#upload-file-parent-id").val($("#file-folder-id").attr("parent-id"));
        $("#upload-file-dialog-id").dialog('open')

        // 发送AJAX请求
        $.ajax({
            url: /*[[@{/file/upload}]]*/'', // 后端接口路径
            type: "POST",
            data: formData,
            contentType: false, // 必须为false（让浏览器自动设置multipart/form-data）
            processData: false, // 禁止jQuery处理数据（避免破坏文件格式）
            success: function(res) {
                // 上传成功后可刷新文件列表
                loadFileList();
                // 隐藏上传框并清空选择
                document.getElementById("uploadDialog").style.display = "none";
                fileInput.value = "";
            },
            error: function(xhr) {

            }
        });
    }

</script>

</body>
</html>
